package hrms.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import hrms.dao.ArticleMapper;
import hrms.entity.Article;
import hrms.util.PageRequest;
import hrms.util.PageResult;
import hrms.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("ArticleService")
public class ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    public void addArticle(Article article){
        articleMapper.insert(article);
    }

    public void deleteArticle(int id){
        articleMapper.deleteByPrimaryKey(id);
    }

    public Article findArticleById(int id){
        return articleMapper.selectByPrimaryKey(id);
    }

    public void editArticle(Article article) { articleMapper.updateByPrimaryKey(article); }

    public List<Article> findAllArticles(){
        return articleMapper.selectAll();
    }

    public PageResult findPage(PageRequest pageRequest) {
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    /**
     * 调用分页插件完成分页
     * @param pageQuery
     * @return
     */
    private PageInfo<Article> getPageInfo(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Article> sysMenus = articleMapper.selectPage();
        return new PageInfo<Article>(sysMenus);
    }

    // 查找特定分类下的所有文章
    public PageResult findPage(PageRequest pageRequest, Integer id) {
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest, id));
    }

    /**
     * 调用分页插件完成分页
     * @param pageQuery
     * @return
     */
    private PageInfo<Article> getPageInfo(PageRequest pageRequest, Integer id) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Article> sysMenus = articleMapper.selectSortPage(id);
        return new PageInfo<Article>(sysMenus);
    }
}
